package org.example.shiro.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.example.shiro.entity.User;
import org.example.shiro.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class CustomerRealm extends AuthorizingRealm{

    @Autowired
    private UserService userService;


    /**
     * 自定义授权方法 获取当前登录用户权限信息,返回给Shiro用来进行授权对比
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("进入自定义授权");
        //1.获取当前用户身份信息
        String principal = principalCollection.getPrimaryPrincipal().toString();
        //2.调用接口方法获取用户的角色信息(从数据库)
        List<String> roles = userService.getUserRoleInfo(principal);
        System.out.println("当前用户角色信息:" + roles);
        //调用接口方法获取用户角色的权限信息
        List<String> permissions = userService.getUserPermissionInfo(roles);
        System.out.println("当前用户权限信息:" + permissions);
        //3.创建对象,存储当前登录的用户的权限和角色
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //4.存储角色
        info.addRole("admin");
        //5. 存储权限
        info.addStringPermissions(permissions);
        //6.返回
        return info;
    }

    /**
     * 自定义登录认证方法
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1.获取token中的用户名
        String principal = authenticationToken.getPrincipal().toString();
        //2.从数据库查:调用业务层获取用户信息(数据库中)
        User user = userService.getUserInfoByName(principal);
        //3.判断并将数据完成封装
        if(user != null){
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                    authenticationToken.getPrincipal(),
                    user.getPwd(),
                    ByteSource.Util.bytes("salt"),
                    this.getName()
            );
            return info;
        }

        return null;
    }
}

